home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++,rb.technical
- Subject: Re: Can copy constructor and operator= share code?
- Followup-To: comp.lang.c++,rb.technical
- Date: 12 Mar 1996 14:21:12 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Message-ID: <4i418o$8nu@dawn.mmm.com>
- References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <VA.00000053.00cdab05@fred> <4i20vi$t6h@news.eunet.ch>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- rop@dial.eunet.ch wrote:
- > What about :
-
- > T::T(const T&t)
- > {
- > *this =t;
- > }
-
- > That's what I am always using.
-
- As has been posted before, this can cause problems in a class
- which must release resources. Suppose, for example, that T is
- a String class which dynamically allocates memory and stores a
- pointer to it.
-
- If the assignment operator is to allocate new memory for a copy
- of the new string, it must either delete the current memory it
- holds, or there will be a memory leak.
-
- Assuming that the assignment operator deletes its current memory,
- the copy constructor above will be problematic because the pointer
- is not initialized, and a garbage pointer will be deleted.
-
- Calling the assignment operator from the copy constructor can work,
- but the members must be initialized first.
- --
- Kevin J. Hopps, 3M Company kjhopps@mmm.com
- Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-